# -*-coding:utf-8-*-
import platform
import urllib.request
import json
import os
import traceback
import shutil

server_addr = ""
server_port = ""
server_token = ""


class Conf:
    def __init__(self, name, connect_type, local_ip, local_port, remote_port):
        self.name = name
        self.type = connect_type
        self.local_ip = local_ip
        self.local_port = local_port
        self.remote_port = remote_port


if __name__ == "__main__":
    system_name = platform.system().lower()
    machine_name = platform.machine().lower()[-2:]
    if machine_name == "64":
        machine_name = "amd64"
    elif machine_name == "86":
        machine_name = "386"
    print(system_name)
    print(machine_name)

    # get latest release
    print("Download frp, please wait…")
    try:
        github_api_return = urllib.request.urlopen("https://api.github.com/repos/fatedier/frp/releases/latest").read()
        github_api_json = json.loads(github_api_return.decode())
        download_url = ""
        for i in github_api_json["assets"]:
            if system_name in i["name"] and machine_name in i["name"]:
                download_url = i["browser_download_url"]
                break
        print(download_url)
        assert download_url
        urllib.request.urlretrieve(download_url, filename="frp.tar.gz")
    except Exception as e:
        print("\033[31mnetwork error!\033[0m")
        traceback.print_exc()

    # decompression frp
    try:
        shutil.rmtree("frp")
    except FileNotFoundError:
        pass
    os.mkdir("frp")
    os.system("tar -xvf frp.tar.gz -C frp --strip-components 1")

    print("***Start config Server information***")
    server_addr = input("Server addr:")
    server_port = int(input("Server port[7000]:") or 7000)
    server_token = input("Server token[]:")
    config = []
    while True:
        print("******config service******")
        name = input("Service name:")
        _type = input("Service type[tcp]:") or "tcp"
        addr = input("Local address[localhost]:") or "localhost"
        port = input("Local port:")
        remote_port = input("Remote port:")
        config.append(Conf(name, _type, addr, port, remote_port))
        flag = input("Add more?(y/N):") or "N"
        if flag == "y" or flag == "Y":
            continue
        break

    with open("frp/frpc.ini", "w") as f:
        f.write("[common]\r\n")
        f.write("server_addr = %s\r\n" % server_addr)
        f.write("server_port = %s\r\n" % server_port)
        f.write("token = %s\r\n" % server_token)

        for c in config:
            f.write("\r\n[%s]\r\n" % c.name)
            f.write("type = %s\r\n" % c.type)
            f.write("local_ip = %s\r\n" % c.local_ip)
            f.write("local_port = %s\r\n" % c.local_port)
            f.write("remote_port = %s\r\n" % c.remote_port)
            f.writelines(["use_encryption = true\r\n", "use_compression = true\r\n"])
    path = os.path.dirname(os.path.abspath(__file__))

    systemd_config = """[Unit]
Description=FRP Client Daemon
After=network.target
Wants=network.target

[Service]
Type=simple
User=root
ExecStart=%s/frp/frpc -c %s/frp/frpc.ini
Restart=always
RestartSec=20s

[Install]
WantedBy=multi-user.target
""" % (path, path)
    with open("frp/frpc.service", "w") as f:
        f.write(systemd_config)
